package com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.impl;


import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.core.jdbc.service.parse.type.impl.sql.BeeSqlPrase;
import com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.IBeeSqlPrase;
import com.mjk.common.tools.springextend.BeeSpringBean;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * if标签解析
 * @author Administrator
 *
 */
public class BeeSqlIfPrase implements IBeeSqlPrase {
	/**
	 * 解析if条件
	 * @param sql
	 * @return
	 */
	public  String praseSql(String sql,Map<String,Object> params ) {
		BeeSqlPrase prase = BeeSpringBean.getBean(BeeSqlPrase.class);
        Pattern pattern = Pattern.compile(BeeCommonConstns.IF_MATCH, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(sql);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String condition = matcher.group(1);
            String content = matcher.group(2);
            try {
	            if (isMatch(condition, params)) {
	            	Pattern r = Pattern.compile(BeeCommonConstns.SET_PARAMS_MATH);
            		Matcher m = r.matcher(content);
            		if(m.find()) {	            		
            			prase.paraseSql(content, params);
            		}else {
            			matcher.appendReplacement(sb, content);
            		}
	            } else {
	                matcher.appendReplacement(sb, "");
	            }
            }catch(Exception e) {//获取不到默认为空
            	 matcher.appendReplacement(sb, "");
            }
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
